package com.sunday.common.core.enums.annotation;

import com.sunday.common.core.enums.ErrorCodeEnum;
import com.sunday.common.core.enums.utils.EnumsUtils;
import com.sunday.common.core.validation.annotation.ErrorCodeAttribute;
import jakarta.validation.Constraint;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import jakarta.validation.Payload;
import org.springframework.core.annotation.AliasFor;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@ErrorCodeAttribute
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {ContainsEnum.ContainsEnumValidator.class})
public @interface ContainsEnum {

    Class<? extends Enum<?>> enumType();

    /**
     * A0_420(ErrorClassifyEnum.A + "0420", "请求参数值超出允许的范围")
     */
    @AliasFor(annotation = ErrorCodeAttribute.class)
    ErrorCodeEnum errorCodeEnum() default ErrorCodeEnum.A0_420;

    String message() default "";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};


    class ContainsEnumValidator implements ConstraintValidator<ContainsEnum, Object> {

        private ContainsEnum containsEnum;

        public void initialize(ContainsEnum containsEnum) {
            this.containsEnum = containsEnum;
        }

        @Override
        public boolean isValid(Object value, ConstraintValidatorContext context) {
            return EnumsUtils.isValid(containsEnum.enumType(), value);
        }

    }

}
